package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.springboot.controller.dto.LoginDTO;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.controller.request.LoginRequest;
import com.example.springboot.entity.Admin;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.AdminMapper;
import com.example.springboot.service.IAdminService;
//import com.example.springboot.utils.TokenUtils;
import com.example.springboot.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//使用指定类初始化日志对象，在日志输出的时候，可以打印出日志信息所在的类
@Slf4j
@Service
//@Service注解将AdminService转为spring的一个组件
public class AdminService implements IAdminService {

    @Autowired //通过autowired导入adminMapper
    AdminMapper adminMapper;

    private static final String DEFAULT_PASS="123";
    private static final String PASS_SALT="sixia";

    @Override
    public List<Admin> list() {
//        有时需要try catch处理来解决函数存在的问题
        return adminMapper.list();
    }

    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest){
//        dependency引入pagehelper
//        PageHelper传入页面和每页信息条数
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Admin> admins=adminMapper.listByCondition(baseRequest);
        return new PageInfo<>(admins);
    }

    @Override
    public void save(Admin admin){//        当做卡号来处理
        Date date= new Date();
//     通过hashCode编码将fastSimpleUUID产生的字母和数字转为数字
        admin.setNickName(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        if(StrUtil.isBlank(admin.getPassword())){
            admin.setPassword(DEFAULT_PASS);
        }
        admin.setPassword(securePass(admin.getPassword()));//设置md5加密
        try{
            adminMapper.save(admin);
        }catch(DuplicateKeyException e){
            log.error("数据插入失败,nickName:{}",admin.getNickName());
            throw new ServiceException("用户插入失败");
        }
    }

    //  通用代码封装 md5加密
    private String securePass(String password){
        return SecureUtil.md5(password+PASS_SALT);
    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }

    @Override
    public void update(Admin admin) {
        admin.setUpdateTime(new Date());
        adminMapper.updateById(admin);

    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public LoginDTO login(LoginRequest request) {

        Admin admin = null;
        try{
            admin = adminMapper.getByAdminName(request.getAdminName());
        }catch(Exception e){
            log.error("根据用户名{}查询出错",request.getAdminName());
            throw new ServiceException("用户名出错");
        }
//        Admin admin=adminMapper.getByUserNameAndPassword(request.getUsername(),request.getPassword());
        if(admin == null){
//            业务层应当返回一个业务对象,而非结果对象? 这句话咋理解
            throw new ServiceException("用户名或密码错误");
        }
//        判断密码是否合法
        String securePass = securePass(request.getPassword());
        if(!securePass.equals(admin.getPassword())){
            throw new ServiceException("密码错误");
        }
        /*if(!admin.isStatus()){
//            业务层应当返回一个业务对象,而非结果对象? 这句话咋理解
            throw new ServiceException("当前用户处于禁用状态,请联系管理员");
        }  管理员状态这个该如何处理*/
        LoginDTO loginDTO=new LoginDTO();
        BeanUtils.copyProperties(admin,loginDTO);

//        生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());
        loginDTO.setToken(token);
        return loginDTO;

    }


}
